/*
 *  Copyright 2019-2023 Zheng Jie
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *  http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */
package me.zhengjie.config.mybatis;

import cn.hutool.core.date.DateTime;
import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.baomidou.mybatisplus.extension.toolkit.SqlRunner;
import me.zhengjie.utils.SecurityUtils;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;

import java.lang.reflect.Array;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

/**
 * @author Zheng Jie
 * @description
 * @date 2023-06-13
 **/
@Component
public class MyMetaObjectHandler implements MetaObjectHandler {


    @Override
    public void insertFill(MetaObject metaObject) {
        /* 创建时间 */
        this.setFieldValByName("createTime", DateTime.now().toTimestamp(), metaObject);
        this.setFieldValByName("updateTime", DateTime.now().toTimestamp(), metaObject);


        /* 操作人 */
        String username = "System";
        try {username = SecurityUtils.getCurrentUsername();}catch (Exception ignored){}
        this.strictInsertFill(metaObject, "createBy", String.class, username);
        this.strictInsertFill(metaObject, "updateBy", String.class, username);
        this.updateTrainResult(metaObject, "insert");
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        System.out.println("updateFill " );

        /* 更新时间 */
        this.setFieldValByName("updateTime", DateTime.now().toTimestamp(), metaObject);
        /* 操作人 */
        String username = "System";
        try {username = SecurityUtils.getCurrentUsername();}catch (Exception ignored){}
        this.setFieldValByName("updateBy", username, metaObject);

        this.updateTrainResult(metaObject, "update");

    }

    private void updateTrainResult(MetaObject metaObject, String type) {
        // FIXME: 暂时在此处统一处理Train表格的result字段
        try {
            String className = metaObject.getOriginalObject().getClass().getSimpleName();
            if (!className.contains("Train")) {
                return;
            }

            int result = (int) metaObject.getValue("result") >= 3  ? 0 : 1;
            long trainId = (long) metaObject.getValue("trainId");
            long trainItemId = (long) metaObject.getValue("trainItemId");

            String updateSql = String.format("UPDATE train_trains_items SET result = %d WHERE train_id = %d AND item_id = %d", result, trainId, trainItemId);
            SqlRunner.db().update(updateSql);
            if (type.equals("insert")) {
//                SqlRunner.db().insert("INSERT INTO train_statistic (train_id, train_item_id) VALUES ({0}, {1})", trainId, trainItemId);
                String insertSql = String.format("INSERT INTO train_statistic (train_id, train_item_id) VALUES (%d, %d)", trainId, trainItemId);
                SqlRunner.db().insert(insertSql);
            }
            SqlRunner.db().close();

        } catch (Exception e) {
            System.out.println("update train result error:" + e.getMessage());
        }
    }
}

